<?php
Class Day21_detail_data{
    public function post(){
        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        $length = isset($_POST['length']) ? $_POST['length'] : 10;
        $habitid = isset($_POST['habitid']) ? $_POST['habitid'] : "";
        if($habitid==""){
            exit(json_encode(array('code' => '01', 'msg' => '评论id为空')));
        }else{
            $getList = $this->getList($habitid,$page,$length);
            $totalPage = $this->getTotalPage($habitid,$length);
            array_unshift($getList,array('total'=>$totalPage));
            exit(json_encode($getList));
        }
    }

    /**
     * @param $habitid
     * @param $page
     * @param $length
     * @return array
     */
    private function getList($habitid,$page,$length){
        $sql = 'SELECT nickname,content,ctime From day21_habit_comments WHERE habitid=:habitid ORDER BY ctime DESC ';
        $sql .= ' LIMIT '.($page-1)*$length.','.$length;
        $query = MySQL::getInstance()->prepare($sql);
        $query->bindValue(":habitid",$habitid,PDO::PARAM_INT);
        $query->execute();
        return  $query->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * @param $kwd
     * @param $length
     * @return float
     */
    private function getTotalPage($habitid,$length){
        $sql = 'SELECT COUNT(*) AS total FROM day21_habit_comments WHERE  habitid=:habitid ';
        $query = MySQL::getInstance()->prepare($sql);
        $query->bindValue(":habitid",$habitid,PDO::PARAM_INT);
        $query->execute();
        $res = $query->fetch(PDO::FETCH_ASSOC);
        return ceil($res['total']/$length);
    }

}